package com.fenxiangle.yueding.feature.common.view;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.util.RxKeyboardTool;
import com.fenxiangle.yueding.entity.bo.UnMsgBo;
import com.fenxiangle.yueding.entity.bo.UnReadCountBo;
import com.fenxiangle.yueding.feature.focus.view.FocusFragment;
import com.fenxiangle.yueding.feature.home.view.HomeFragment;
import com.fenxiangle.yueding.feature.message.view.MessageFragment;
import com.fenxiangle.yueding.feature.mine.view.MineFragment;
import com.fenxiangle.yueding.feature.publish.view.PublishRequirementActivity;
import com.fenxiangle.yueding.framework.DataServer;
import com.fenxiangle.yueding.framework.api.HomeApi;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.leolin.shortcutbadger.ShortcutBadger;

import static com.suozhang.framework.utils.AppUtil.fullScreen;


public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {


    @BindView(R.id.radiogroup)
    RadioGroup mRadiogroup;

    @BindView(R.id.rb_home_lottery)
    RadioButton mRbHomeLottery;
    @BindView(R.id.rb_home_documentary)
    RadioButton mRbHomeDocumentary;
    @BindView(R.id.rb_home_find)
    RadioButton mRbHomeFind;
    @BindView(R.id.rb_home_mine)
    RadioButton mRbHomeMine;
    @BindView(R.id.btn_add)
    RelativeLayout mBtnAdd;
    @BindView(R.id.btn_home_msg)
    CheckBox btnHomeMsg;

    @BindView(R.id.btn_home_mine)
    CheckBox btnHomeMine;

    @BindView(R.id.iv_msg_tip)
    ImageView ivMsgTip;
    @BindView(R.id.iv_mine_tip)
    ImageView ivMineTip;
    @BindView(R.id.btn_home_home)
    CheckBox btnHomeHome;
    @BindView(R.id.btn_home_focus)
    CheckBox btnHomeFocus;

    private HomeFragment mHomeFragment;
    public MessageFragment mMessageFragment;
    private FocusFragment mFocusFragment;
    private MineFragment mMineFragment;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initView() {
        RxKeyboardTool.hideSoftInput(this);
        mHomeFragment = new HomeFragment();
        mMessageFragment = new MessageFragment();
        mFocusFragment = new FocusFragment();
        mMineFragment = new MineFragment();
        addFragment(R.id.fl_container, mHomeFragment);
    }

    @Override
    protected void initData() {
        showContacts(this);
        getMsgCount();



    }

    private void getMsgCount() {
        AM.api().createApiService(HomeApi.class)
                .selectDiffMessageCount(new UnMsgBo(0 + ""))
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<UnReadCountBo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UnReadCountBo msgBos) {
                        if (msgBos != null) {
                            if (msgBos.getMessageCenterTotal() > 0) {
                                ivMsgTip.setVisibility(View.VISIBLE);
                            } else {
                                ivMsgTip.setVisibility(View.GONE);
                            }
                            if (msgBos.getUserCenterTotal() > 0) {
                                ivMineTip.setVisibility(View.VISIBLE);
                            } else {
                                ivMineTip.setVisibility(View.GONE);
                            }

                            if(msgBos.getUserCenterTotal()>0){
                                ShortcutBadger.applyCount(MainActivity.this, msgBos.getUserCenterTotal());
                            }else {
                                ShortcutBadger.removeCount(MainActivity.this);
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void showContacts(Activity activity) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
//            ToastUtils.getInstance().show(this,"没有权限,请手动开启定位权限");
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, 100);
        } else {
//            startLocation();
        }
    }

    @Override
    protected void initEvent() {
        mRadiogroup.setOnCheckedChangeListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 20005) {

            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if (selectList != null && selectList.size() > 0) {
                Intent intent = new Intent();
                intent.putExtra("status", (Serializable) selectList);
                intent.setAction("com.emay.power.MyBroadCastReceiver");
                sendBroadcast(intent);

            }
//            RxBus.getDefault().post(new EventEntity(8, ""));

        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {

            case R.id.rb_home_lottery:

                break;
            case R.id.rb_home_documentary:

                break;

        }
        btnHomeMsg.setChecked(false);
        btnHomeMine.setChecked(false);

    }

    @OnClick({R.id.view_home_home, R.id.view_home_focus, R.id.view_home_msg, R.id.view_home_mine})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_home_home:
                replaceFragment(R.id.fl_container, mHomeFragment);
                btnHomeHome.setChecked(true);
                btnHomeFocus.setChecked(false);
                btnHomeMsg.setChecked(false);
                btnHomeMine.setChecked(false);
                break;
            case R.id.view_home_focus:
                replaceFragment(R.id.fl_container, mFocusFragment);
                btnHomeHome.setChecked(false);
                btnHomeFocus.setChecked(true);
                btnHomeMsg.setChecked(false);
                btnHomeMine.setChecked(false);
                break;
            case R.id.view_home_msg:
                replaceFragment(R.id.fl_container, mMessageFragment);
                btnHomeHome.setChecked(false);
                btnHomeFocus.setChecked(false);
                btnHomeMsg.setChecked(true);
                btnHomeMine.setChecked(false);
                getMsgCount();
                break;
            case R.id.view_home_mine:
                replaceFragment(R.id.fl_container, mMineFragment);
                btnHomeHome.setChecked(false);
                btnHomeFocus.setChecked(false);
                btnHomeMsg.setChecked(false);
                btnHomeMine.setChecked(true);
                getMsgCount();
                break;
        }


    }


    //退出时的时间
    private long mExitTime;

    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            T.showShort("再按一次退出常约定！");
            mExitTime = System.currentTimeMillis();
        } else {
            AM.appManager().exitApp();
        }
    }


    @OnClick(R.id.btn_home_wode)
    public void onViewClicked() {
        Intent intent = new Intent(this, PublishRequirementActivity.class);
        startActivity(intent);
    }


    @Override
    protected void initSystemParams() {
//        super.initSystemParams();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        fullScreen(this);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
